using B.S.XZYData.Api.Wrter.Application.Command.Team;
using B.S.XZYData.Domain.XZY;
using B.S.XZYData.ErrorCode;
using B.S.XZYData.Infrastructure;
using MediatR;

namespace B.S.XZYData.Api.Wrter.Application.Handler.Team
{
    /// <summary>
    /// 编辑班组处理器
    /// </summary>
    public class UpdateTeamHandler : IRequestHandler<UpdateTeamCommand, ApiResult<bool>>
    {
        private readonly MyDbContext _dbContext;

        public UpdateTeamHandler(MyDbContext dbContext)
        {
            _dbContext = dbContext;
        }

        public async Task<ApiResult<bool>> Handle(UpdateTeamCommand request, CancellationToken cancellationToken)
        {
            try
            {
                // 添加调试日志
                Console.WriteLine($"接收到更新班组请求: TeamId={request.TeamId}, TeamName={request.TeamName}");
                Console.WriteLine($"班组成员数量: {request.TeamMembers?.Count ?? 0}");
                if (request.TeamMembers != null)
                {
                    foreach (var member in request.TeamMembers)
                    {
                        Console.WriteLine($"成员: Id={member.Id}, Name={member.MemberName}, IsDeleted={member.IsDeleted}");
                    }
                }
                
                // 检查班组是否存在
                var existingTeam = await _dbContext.Team.InSingleAsync(request.TeamId);
                if (existingTeam == null || existingTeam.IsDeleted)
                {
                    return new ApiResult<bool>
                    {
                        Code = ApiEnum.Fail,
                        Msg = "班组不存在",
                        Data = false
                    };
                }

                // 更新班组基本信息
                existingTeam.TeamName = request.TeamName;
                existingTeam.TeamCode = request.TeamCode;
                existingTeam.TeamType = request.TeamType;
                existingTeam.Remark = request.Remark;
                existingTeam.ModifyTime = DateTime.Now;
                existingTeam.ModifierId = 1; // 这里应该从当前登录用户获取

                await _dbContext.Updateable(existingTeam).ExecuteCommandAsync();

                // 处理班组成员 - 先逻辑删除所有现有成员，然后新增前端传过来的数据
                if (request.TeamMembers != null)
                {
                    // 1. 先逻辑删除该班组的所有现有成员
                    var existingMembers = await _dbContext.TeamMember
                        .Where(x => x.TeamId == request.TeamId && !x.IsDeleted)
                        .ToListAsync();

                    foreach (var existingMember in existingMembers)
                    {
                        existingMember.IsDeleted = true;
                        existingMember.ModifyTime = DateTime.Now;
                        existingMember.ModifierId = 1; // 这里应该从当前登录用户获取
                        await _dbContext.Updateable(existingMember).ExecuteCommandAsync();
                    }

                    // 2. 新增前端传过来的班组成员数据
                    var activeMembers = request.TeamMembers.Where(x => !x.IsDeleted).ToList();
                    foreach (var memberRequest in activeMembers)
                    {
                        var newMember = new TeamMember
                        {
                            TeamId = request.TeamId,
                            MemberName = memberRequest.MemberName,
                            MemberRealName = memberRequest.MemberRealName,
                            Phone = memberRequest.Phone,
                            CreateTime = DateTime.Now,
                            CreatorId = 1, // 这里应该从当前登录用户获取
                            IsDeleted = false
                        };

                        await _dbContext.Insertable(newMember).ExecuteCommandAsync();
                    }
                }

                return new ApiResult<bool>
                {
                    Code = ApiEnum.Success,
                    Msg = "编辑班组成功",
                    Data = true
                };
            }
            catch (Exception ex)
            {
                return new ApiResult<bool>
                {
                    Code = ApiEnum.Error,
                    Msg = $"编辑班组失败: {ex.Message}",
                    Data = false
                };
            }
        }
    }
}
